// 供方加扣款结算 详情
<template>
    <!-- 集采汇总编辑页 -->
    <div class="e-form">
        <BillTop title="供方加扣款结算详情" @cancel="handleClose"></BillTop>
        <!-- //详情 添加页面 ↓ -->
        <div class="tabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="加扣款明细"
                    name="planDetail"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="返还保证金"
                    name="fhbzj"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <!-- <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane> -->
                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        ref="rulesBaseRef"
                                        :rules="rulesBase"
                                        :model="formData"
                                        label-width="150px"
                                    >
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算编号："
                                                    prop="billNo"
                                                >
                                                    <!-- <el-input v-model="formData.billNo"></el-input> -->
                                                    <span>{{
                                                        formData.billNo
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="单据机构："
                                                    prop="orgName"
                                                >
                                                    <!-- <el-input v-model="formData.settlementUnitName"></el-input> -->
                                                    <span>{{
                                                        formData.orgName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="合同类型："
                                                    prop="contractType"
                                                >
                                                    <span>{{
                                                        [
                                                            '物资采购',
                                                            '周材租赁',
                                                            '加工',
                                                            '设备采购',
                                                            '设备租赁',
                                                            '服务采购'
                                                        ][
                                                            formData.contractType -
                                                                1
                                                        ]
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="合同名称："
                                                    prop="contractName"
                                                >
                                                    <span>
                                                        {{
                                                            formData.contractName
                                                        }}
                                                        <i
                                                            slot="suffix"
                                                            class="
                                                                el-input__icon
                                                                el-icon-document-copy
                                                            "
                                                            @click="
                                                                contractNameClick
                                                            "
                                                            v-if="
                                                                formData.contractName
                                                            "
                                                        ></i>
                                                    </span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="结算单位："
                                                    prop="settlementUnitName"
                                                >
                                                    <span>{{
                                                        formData.settlementUnitName
                                                    }}</span>
                                                    <!-- <el-input v-model="formData.settlementUnitName" :disabled="true"></el-input> -->
                                                    <!-- <el-button size="small"
                            style="background: rgb(75, 178, 255); color: #fff" @click="truejcht">选择机材合同</el-button> -->
                                                    <!-- <span>{{formData.settlementUnitName}}</span> -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="加扣款日期："
                                                    prop="settlementDate"
                                                >
                                                    {{
                                                        formData.settlementDate
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="加扣款金额(元)："
                                                    prop='plusDeductionAmount'
                                                >
                                                    <span>{{
                                                        formData.plusDeductionAmount
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <!-- 返回id、名字 -->
                                                <el-form-item
                                                    label="返还保证金金额(元)："
                                                    prop='returnDepositAmount'
                                                >
                                                    <span>{{
                                                        formData.returnDepositAmount
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="币种：">
                                                    <span>{{
                                                        formData.currency
                                                    }}</span>
                                                    <!-- <el-input v-model="formData.currency"></el-input> -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="传财务共享："
                                                >
                                                    {{ formData.easId ? '已传' : '未传'}}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="本位币："
                                                    prop="baseCurName">
                                                    <span>{{
                                                        formData.baseCurName
                                                    }}</span>
                                                    <!-- <el-input v-model="formData.baseCurName"></el-input> -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="状态："
                                                    prop="state">
                                                    {{
                                                        showState(
                                                            formData.state
                                                        )
                                                    }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="本位币汇率："
                                                    prop='baseCurRate'
                                                >
                                                    <!-- <el-input v-model="formData.baseCurRate"></el-input> -->
                                                    <span>{{
                                                        formData.baseCurRate
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="录入人："
                                                    prop='founderName'>
                                                    <!-- <el-input v-model="formData.baseCurRate"></el-input> -->
                                                    <span>{{
                                                        formData.founderName
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row>
                                            <el-col :span="24">
                                                <el-form-item label="备注：">
                                                    <span>{{
                                                        formData.remarks
                                                    }}</span>
                                                    <!-- <el-input type="textarea" :rows="2" laceholder="请输入内容" v-model="formData.remarks"></el-input> -->
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row v-if="formData.state == 5">
                                            <el-col :span="12">
                                                <el-col :span="12">
                                                    <el-form-item
                                                        label="作废人："
                                                    >
                                                        <span>{{
                                                            formData.nullifyCreator
                                                        }}</span>
                                                    </el-form-item>
                                                </el-col>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废时间："
                                                >
                                                    <span>{{
                                                        formData.nullifyCreated
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>

                                        <el-row v-if="formData.state == 5">
                                            <el-col :span="12">
                                                <el-col :span="12">
                                                    <el-form-item
                                                        label="作废原因："
                                                    >
                                                        <span>{{
                                                            formData.nullifyReason
                                                        }}</span>
                                                    </el-form-item>
                                                </el-col>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="作废说明："
                                                >
                                                    <span>{{
                                                        formData.nullifyDescription
                                                    }}</span>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 加扣款明细 -->
                    <div id="planDetailCon" class="con">
                        <div class="tabs-title" id="planDetail">加扣款明细</div>
                        <el-tabs
                            :class="'childTab ' + childTabClass"
                            tab-position="left"
                            v-model="tabsNameChild"
                            @tab-click="onChangeTab"
                        >
                            <el-tab-pane
                                label="加扣款"
                                name="materialDetails"
                                :disabled="clickTabFlag"
                            ></el-tab-pane>
                            <el-tab-pane
                                label="物资明细"
                                name="technicalParameter"
                                :disabled="clickTabFlag"
                            ></el-tab-pane>
                            <div>
                                <div id="planDetailCon">
                                    <div
                                        class="tabs-title"
                                        id="materialDetails"
                                    >
                                        加扣款
                                    </div>
                                    <div class="e-table">
                                        <el-table
                                            :data="jkktableData"
                                            ref='jkktable'
                                            border
                                            style="width: 100%"
                                            :row-class-name="tableRowClassName"
                                            @selection-change="planTableSelect"
                                            :max-height="$store.state.tableHeight"
                                            v-sortTable="{ 'tableData': jkktableData, '_this': this, 'ref': 'jkktable' }"
                                        >
                                            <el-table-column
                                                label="加扣款名称"
                                                min-width="200"
                                            >
                                                <template slot-scope="{ row }">
                                                    {{ row.plusDeductionName }}
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="加扣款类别"
                                                min-width="100"
                                            >
                                                <template slot-scope="{ row }">
                                                    {{
                                                        row.plusDeductionType - 0 == 1
                                                            ? '加款'
                                                            : '扣款'
                                                    }}
                                                </template>
                                            </el-table-column>
                                            <el-table-column
                                                label="规格"
                                                min-width="300"
                                                prop='spec'
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                label="单位"
                                                min-width="300"
                                                prop='unit'
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                label="加扣款金额"
                                                min-width="300"
                                                prop='amount'
                                            >
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>

                                <div id="planDetailCon">
                                    <div
                                        class="tabs-title"
                                        id="technicalParameter"
                                    >
                                        物资汇总
                                    </div>
                                    <div class="e-table">
                                        <el-table
                                            :data="wzmxtable"
                                            ref='wzmxtable'
                                            border
                                            style="
                                                width: 100%;
                                                margin-top: 20px;
                                            "
                                            @selection-change="planTableSelect"
                                            :tree-props="{
                                                children: 'children',
                                                hasChildren: 'hasChildren'
                                            }"
                                            row-key="uuid"
                                            :max-height="$store.state.tableHeight"
                                            v-sortTable="{ 'tableData': wzmxtable, '_this': this, 'ref': 'wzmxtable' }"
                                        >
                                            <el-table-column
                                                prop="topClassName"
                                                label="物资类别"
                                                width="150"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="materialName"
                                                label="物资名称"
                                                min-width="200"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="spec"
                                                label="规格"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="texture"
                                                label="材质"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                prop="unit"
                                                label="单位"
                                                width="100"
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                label="金额"
                                                width="100"
                                                prop='amount'
                                            >
                                            </el-table-column>
                                            <el-table-column
                                                label="分摊比例"
                                                width="100"
                                                prop='apportionmentRatio'
                                            >
                                            </el-table-column>
                                        </el-table>
                                    </div>
                                </div>
                            </div>
                        </el-tabs>
                    </div>

                    <!-- 返还保证金 -->
                    <div id="fhbzjCon" class="con">
                        <div class="tabs-title" id="fhbzj">返还保证金</div>
                        <div class="e-table" style="min-height: auto">
                            <el-table
                                :data="bzjtableData"
                                border
                                style="width: 100%"
                                ref='marginTableRef'
                                :row-class-name="tableRowClassName"
                                @selection-change="marginSelect"
                                :max-height="$store.state.tableHeight"
                                v-sortTable="{ 'tableData': bzjtableData, '_this': this, 'ref': 'marginTableRef' }"
                            >
                                <el-table-column label="保证金名称" prop='returnDepositName' width="150">
                                </el-table-column>
                                <el-table-column
                                    prop="withholdAmount"
                                    label="暂扣保证金(元)"
                                    width="250"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="previousTotalReturnedAmount"
                                    label="截止上期末未返还保证金(元)"
                                    width="250"
                                >
                                </el-table-column>
                                <el-table-column
                                    label="返还保证金(元)"
                                    width="200"
                                    prop='returnAmount'
                                >
                                </el-table-column>
                                <el-table-column
                                    label="截止本期末未返还保证金(元)"
                                    width="200"
                                    prop='currentTotalNotReturnedAmount'
                                >
                                </el-table-column>
                                <el-table-column label="说明" width="250" prop='remarks'>
                                </el-table-column>
                            </el-table>
                        </div>
                        <!-- <ComPagination /> -->
                    </div>

                    <!-- 附件信息 -->
                    <div id="accessoryCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                            isView
                        />
                    </div>

                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                                <ComAuditHistoryIndex
                                    :billType="1019"
                                    :tableData.sync="shenheArr"
                                    @getAuditHistory="getauditHistory"
                                    ref="AuditHistoryRef"
                                />
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <exaButtons
                :auditState="auditState"
                @exas="exas"
                v-if="formData.state !== 5"
                :state="formData.state - 0"
                :founderId="formData.founderId"
                :isPrint="formData.state === 1 || formData.state === 2"
            ></exaButtons>
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import AttachComp from '@/components/common/attachIndex'
import { selectDataClient, openAppClient, showLoading, hideLoading, getUuid } from '@/utils/common'
import { getUnit } from '@/api/subcontractApi/currency.js'
import auditRequest from '@/api/materialSettlement/supplierAddpayment.js'
import publicRequest from '@/api/materialSettlement/public.js'
import exaButtons from '@/components/common/exaButtons'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
import { webprintReport, numToChinese } from '@/utils/common'

export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        exaButtons
    },
    data () {
        return {
            //我的数据:↓
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1019',
                nullifyDescription: '',
                nullifyReason: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            shenheArr: [],
            billId: '',
            state: '',
            formData: {
                baseCurId: '',
                baseCurName: '',
                baseCurPlusDeductionAmount: 0,
                baseCurRate: 0,
                baseCurReturnDepositAmount: 0,
                billId: '',
                billNo: '',
                contractBillId: '',
                contractBillNo: '',
                contractName: '',
                contractType: 0,
                currency: '',
                currencyId: '',
                easId: '',
                evaluationLevel: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                plusDeductionAmount: '',
                remarks: '',
                returnDepositAmount: '',
                rmbId: '',
                rmbName: '',
                rmbPlusDeductionAmount: 0,
                rmbRate: 0,
                rmbReturnDepositAmount: 0,
                settlementDate: '', //结算日期
                settlementUnitId: '',
                settlementUnitName: '',
                state: 0,
                workId: ''
            },
            rulesBase: {
                billNo: [
                    {
                        required: true,
                        message: '结算编号不能为空',
                        trigger: 'change'
                    }
                ],
                orgName: [
                    {
                        required: true,
                        message: '机构不能为空',
                        trigger: 'change'
                    }
                ],
                settlementDate: [
                    {
                        required: true,
                        message: '加扣款日期不能为空',
                        trigger: 'change'
                    }
                ],
                contractType: [
                    {
                        required: true,
                        message: '合同类型不能为空',
                        trigger: 'change'
                    }
                ],
                contractName: [
                    {
                        required: true,
                        message: '合同名称不能为空',
                        trigger: 'change'
                    }
                ],
                settlementUnitName: [
                    {
                        required: true,
                        message: '结算单位不能为空',
                        trigger: 'change'
                    }
                ],
                plusDeductionAmount: [
                    {
                        required: true,
                        message: '请计算加扣款金额',
                        trigger: 'change'
                    }
                ],
                returnDepositAmount: [
                    {
                        required: true,
                        message: '请计算返还保证金金额',
                        trigger: 'change'
                    }
                ],
                baseCurName: [
                    {
                        required: true,
                        message: '本位币不能为空',
                        trigger: 'change'
                    }
                ],
                baseCurRate: [
                    {
                        required: true,
                        message: '本位币汇率不能为空',
                        trigger: 'change'
                    }
                ],
            },
            user: {}, //本地储存用户信息
            jkktableData: [],
            wzmxtable: [],
            bzjtableData: [],
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 1019,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            },
            tabsName: 'baseInfo',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            planSelect: [],
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            objFlag: {
                flag5: false
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            dtlIds: '', //
            materialsNameData: [], //机构汇总表
            createHistoryData: [], //明细修改历史列表
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            acceptanceSelects: false,
            tableHeadClass: 'cancelClass',
            resultCount: null,
            remainingApportionmentRatio: null,
            acceptanceList: [],
            marginList: []
        }
    },
    watch: {
        acceptanceSelects () {
            if (this.acceptanceSelects) {
                this.tableHeadClass = 'tableHeadClass'
            } else {
                this.tableHeadClass = 'cancelClass'
            }
        }
    },
    computed: {
        // 我的计算属性 ↓
        jkkje () {
            let num = +(this.jkktableData
                .reduce((prev, c) => (prev += +c.amount || 0), 0))
                .toFixed(2)
            return num
        },
        //加扣款金额本位币
        jkkjeBwb () {
            let num = 0
            if (this.formData.baseCurRate) {
                num = this.jkkje * this.formData.baseCurRate
            }
            return num
        },
        // 基本信息的返还保证金
        bzjje () {
            // let num = 0
            // if (this.bzjtableData.length > 0) {
            //     for (let i = 0; i < this.bzjtableData.length; i++) {
            //         if (this.bzjtableData[i].returnAmount) {
            //             num +=
            //                 this.bzjtableData[i].notReturnedAmount -
            //                 this.bzjtableData[i].returnAmount
            //         } else {
            //             num += this.bzjtableData[i].notReturnedAmount - 0
            //         }
            //         // }
            //     }
            // }
            // return num
            let amount = +(this.bzjtableData.reduce((prev, c) => prev += (+c.returnAmount || 0), 0)).toFixed(2)
            return amount
        },
        //保证金额 本位币
        bzjjeBwb () {
            let num = 0
            if (this.formData.baseCurRate) {
                num = this.bzjje * this.formData.baseCurRate
            }
            return num
        },

        // 我的计算属性 ↑
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm //币种
        }),
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        //状态
        // statusLable () {
        //     return param => {
        //         const state = this.$store.state.settlementManagement.ysState
        //         const obj = state.find(x => x.value == param)
        //         return obj ? obj.label : ''
        //     }
        // }
    },
    async created () {
        this.formData.founderName = localStorage.getItem('userName')
        this.billId = this.$route.query.billid
        this.user = JSON.parse(localStorage.getItem('vuex'))
        this.danweiArr = await getUnit() //获取单位
        this.getCurrentUnitInfo()
        this.getBasic()
    },
    methods: {
        ...mapMutations([
            'setPopConfirm',
            'setSelectedInfo',
            'setHistoryTableData',
            'setAuditParams'
        ]),
        // 获取基本信息
        async getBasic () {
            const data = await auditRequest.getSettlemen({ id: this.billId })
            this.formData = data
            this.formData.state = this.formData.state - 0
            await this.getPlusDeduction()
            await this.getMaterials()
            await this.getMargin()
        },
        // 获取加扣款明细
        async getPlusDeduction () {
            const jkk = await auditRequest.getjkkmxbyId({ id: this.billId })
            this.jkktableData = jkk
        },
        // 获取物资明细
        async getMaterials () {
            let wzmx = await auditRequest.getwzmxbyId({ id: this.billId })
            wzmx.forEach(item => {
                item.materialClassName = item.topClassName
                item.uuid = getUuid()
                item.isChecked = false
                item.children.forEach(i => {
                    i.uuid = i.dtlId
                    i.parentId = item.topClassId
                })
                const count = item.children
                    .reduce((prev, c) => (prev += +c.amount || 0), 0)
                    .toFixed(2)
                item.materialName = `金额小计： ${count}`
            })
            // materialsettle/supplierPlusDeductionSettlement/getListById
            // materialsettle/supplierPlusDeductionSettlement/getReturnDepositDtlListById
            this.wzmxtable = wzmx
        },
        // 获取保证金
        async getMargin () {
            const bzj = await auditRequest.getbzjbyId({ id: this.billId })
            this.bzjtableData = bzj
        },
        // 点击合同名称
        contractNameClick () {
            let url = ''
            let name = ''
            switch (this.formData.contractType) {
            case 1:
                url = '/ctMaterialApplyShow'
                name = '查看物资采购合同'
                break
            case 2:
                url = '/ctRevolvMaterialApplyShow'
                name = '查看周材租赁合同'
                break
            case 3:
                url = '/processingContractApplyShow'
                name = '查看加工合同'
                break
            case 4:
                url = '/ctEquipmentPurchaseApplyShow'
                name = '查看设备采购'
                break
            case 5:
                url = '/ctEquipmentLeaseApplyShow'
                name = '查看设备租赁'
                break
            case 6:
                url = '/serviceProcurementApplyShow'
                name = '查看服务采购合同'
                break
            }
            openAppClient(
                `${url}?billid=${this.formData.contractBillId}&isview=${true}`,
                `${name}`
            )
        },
        // 税率只能输入0-100的数
        onInput0_100 (e) {
            this.$message.closeAll()
            if (e.target.value < 0 || e.target.value > 100) {
                this.clientPop('err', '只能输入[0,100]区间的数')
            }
            e.target.value =
                (e.target.value >= 0 &&
                    e.target.value <= 100 &&
                    e.target.value.match(/^\d{1,3}(\.\d*)?$/)[0]) ||
                null
        },
        //基本信息:选择机材合同弹窗
        async truejcht () {
            selectDataClient({
                SelectServiceToken:
                    '/subcontract/thirdParty/getSupplierSettlement', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [],
                InitParamsStr: JSON.stringify({
                    orgId: this.user.userInfo.orgInfo.orgId
                }),
                Title: '选择合同' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {
                // })
                if (val.length > 0) {
                    this.formData.contractType = val[0].contractType
                    this.formData.contractName = val[0].contractName
                    this.formData.contractBillId = val[0].contractId
                    this.formData.settlementUnitName = val[0].secondPartyName
                    this.formData.settlementUnitId = val[0].secondPartyId
                    this.formData.baseCurId = val[0].baseCurId
                    this.formData.baseCurName = val[0].baseCurName
                    this.formData.currency = val[0].currencyName
                    this.formData.currencyId = val[0].currencyId
                    this.formData.baseCurRate = val[0].baseCurRate
                }
            })
        },
        // ===================================加扣款================================
        //点击新增加扣款
        async addjkk () {
            if (this.formData.settlementUnitId == '') {
                this.clientPop('err', '请选机材合同')
                return
            }
            selectDataClient({
                SelectServiceToken:
                    '/materialsettle/common/getPlusDeductionList', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: '', // 接口参数(name为模拟参数)
                Title: '选择扣款明细' // 标题
            }).then(val => {
                let res = val.map(item => {
                    return {
                        amount: '', //加扣款金额(元)
                        billId: this.billId, // 供方加扣款结算id
                        changeType: 1, //
                        dtlId: '', // 供方加扣款明细id
                        plusDeductionId: item.id, // 加扣款id
                        plusDeductionName: item.name, // 加扣款名称
                        plusDeductionType: item.type, // 加扣款类别
                        spec: '', // 规格型号
                        unit: '' // 计量单位
                    }
                })
                res.forEach(item => {
                    let isPush = this.jkktableData.every(
                        it => item.plusDeductionId !== it.plusDeductionId
                    )
                    if (isPush) {
                        this.jkktableData.push(item)
                    }
                })
            })
        },
        // 加扣款金额变化
        gaibian2 (row) {
            row.changeType === 1 ? row.changeType = 1 : row.changeType = 2
            if (row.plusDeductionType === 2) {
                if (row.amount > 0) {
                    row.amount = -row.amount
                }
            }
        },
        // =============加扣款删除=========
        // 加扣款选中数据
        planTableSelect (selection) {
            this.planSelect = selection.filter(item => item.changeType !== -1)
        },
        // 加扣款删除
        jkkDelete () {
            const length = this.planSelect.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.jkkDeleteList
                )
            }
        },
        // 加扣款批量删除
        jkkDeleteList () {
            this.planSelect.forEach(row => {
                if (row.dtlId) {
                    const index = this.jkktableData.findIndex(item => {
                        return item.dtlId == row.dtlId
                    })
                    this.$set(this.jkktableData[index], 'changeType', -1)
                    this.$set(this.jkktableData[index], 'amount', 0)
                } else {
                    this.jkktableData.forEach((item, index) => {
                        if (this._.isEqual(item, row)) {
                            this.jkktableData.splice(index, 1)
                        }
                    })
                }
            })
            this.$refs.multipleTable1.clearSelection()
        },

        // =====================================物资明细=================================
        //选择物资明细
        async addhtqd () {
            if (this.formData.settlementUnitId == '') {
                this.clientPop('err', '请选机材合同')
                return
            }
            let ids = []
            selectDataClient({
                SelectServiceToken:
                    '/material/categoryLibrary/queryListByParentClassId2',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({ materialType: 0 }),
                Title: '物料选择'
            })
                .then(val => {
                    // this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果')
                    if (this.wzmxtable.length < 1) {
                        this.wzmxtable = this.materialsFn(val)
                    } else {
                        let newArr = this.materialsFn(val)
                        newArr.forEach(item => {
                            const topClassIdRp = this.wzmxtable.every(
                                itm => itm.topClassId != item.topClassId
                            )
                            if (topClassIdRp) {
                                this.wzmxtable.push(item)
                            } else {
                                // 如果数组中的父级id一样,则返回一样的那一项的父级数据
                                const target = this.wzmxtable.find(
                                    its => its.topClassId == item.topClassId
                                )
                                // 给这条父级数据的children里面添加子级
                                item.children.forEach(it => {
                                    // 如果当前父级的子级中没有相同的,则直接添加
                                    const materialIdRp = target.children.every(
                                        _it => _it.materialId != it.materialId
                                    )
                                    if (materialIdRp) {
                                        target.children.push(it)
                                    } else {
                                        // 遍历出所有子级id一样的
                                        const _target = target.children.filter(
                                            i => i.materialId == it.materialId
                                        )
                                        // 如果当前遍历的子项存在于原数组,但是changeTpye等于-1说明已经删除,那还是可以重新添加进入的,changeType不等于-1的,不做操作;如果遍历完了都是等于-1的,才添加
                                        const noPush = _target.some(
                                            _i => _i.changeType !== -1
                                        )
                                        if (!noPush) {
                                            target.children.push(it)
                                        }
                                    }
                                })
                            }
                        })
                    }
                })
                .catch(err => {
                    alert(err)
                })
        },
        // 处理物资明细弹窗拿到的数据
        materialsFn (val) {
            const newArr = []
            let obj = {}
            val.forEach(item => {
                const topClassName = item.classNamePath.split('/')[0]
                const topClassId = item.classIdPath.split('/')[0]
                obj = {
                    topClassId,
                    topClassName,
                    customId: topClassId,
                    materialClassId: topClassId,
                    materialClassName: topClassName,
                    uuid: getUuid(),
                    totalAmount: null,
                    totalQuantity: null,
                    isChecked: false,
                    children: []
                }
                if (newArr.length < 1) {
                    newArr.push(obj)
                } else {
                    let isParent = newArr.every(
                        itm => itm.topClassId !== topClassId
                    )
                    if (isParent) {
                        newArr.push(obj)
                    }
                }
                newArr.forEach(its => {
                    if (
                        its.materialClassId === item.classIdPath.split('/')[0]
                    ) {
                        its.children.push({
                            uuid: getUuid(),
                            customId: getUuid(),
                            amount: '',
                            apportionmentRatio: '', // 分摊比例%
                            billId: this.billId,
                            changeType: 1,
                            contractDtlId: '', // 合同明细id
                            dtlId: '', // 供方加扣款结算物资明细id
                            materialClassId: item.classIdPath
                                .split('/')
                                .slice(1)
                                .join('/'), //物资类别id
                            materialClassName: item.classNamePath
                                .split('/')
                                .slice(1)
                                .join('/'), // 物资类别名称
                            materialId: item.billId, //物资id
                            materialName: item.materialName, //物资名称
                            spec: item.spec, //规格型号
                            texture: '', //材质
                            unit: item.unit, //单位
                            parentId: its.topClassId
                        })
                    }
                    // 统计小计
                    const count = +its.children
                        .reduce((prev, c) => (prev += +c.amount || 0), 0)
                        .toFixed(2)
                    its.materialName = `金额小计： ${count}`
                })
            })
            return newArr
        },

        // 物资明细的金额或比例变化时
        changnum (row, str) {
            row.changeType === 1 ? row.changeType = 1 : row.changeType = 2
            // 填写当前行金额后,当前行分摊比例 = 当前行金额/基本信息的加扣款金额,最后一行的金额=加扣款金额-之前行金额
            // 填写当前行分摊比例,当前行金额 = 当前行分摊比例 * 基本信息的加扣款金额,最后一行分摊比例 = 100 - 之前行的分摊比例
            // apportionmentRatio 比例
            // amount 金额
            let total = 0
            let num = 0
            let count = 0
            this.wzmxtable.forEach(item => {
                item.children.forEach(i => {
                    if (i.changeType !== -1) {
                        count++
                    }
                })
            })
            console.log(count)
            if (this.jkkje > 0) {
                if (str === '金额') {
                    this.wzmxtable.forEach(item => {
                        total += item.children.reduce((prev, cur) => {
                            return prev + Number(cur.amount)
                        }, 0)
                    })
                    console.log(total)
                    if (Math.abs(total) > Math.abs(this.jkkje)) {
                        this.clientPop('err', '超出剩余未分摊金额')
                        row.amount = ''
                        row.apportionmentRatio = ''
                    } else {
                        // this.clientPop('err', `剩余未分摊金额 ${this.jkkje - total}`)
                        row.apportionmentRatio = +(
                            (row.amount / this.jkkje) *
                            100
                        ).toFixed(2)
                    }
                } else if(str === '比例') {
                    this.wzmxtable.forEach(item => {
                        total += item.children.reduce((prev, cur) => {
                            return prev + Number(cur.apportionmentRatio)
                        }, 0)
                    })
                    if (total > 1) {
                        this.clientPop('err', '超出剩余未分摊比例')
                        row.amount = ''
                        row.apportionmentRatio = ''
                    } else {
                        // this.clientPop('err', `剩余未分摊比例 ${this.jkkje - total}`)
                        row.amount = (
                            this.jkkje * row.apportionmentRatio
                        ).toFixed(2)
                    }
                }
            } else if (this.jkkje < 0) {
                if (str === '金额') {
                    console.log(row.amount)
                    row.amount = -row.amount || ''
                    this.wzmxtable.forEach(item => {
                        total += item.children.reduce((prev, cur) => {
                            if (cur.amount !== null && cur.amount !== '') {
                                num++
                            }
                            return prev + Number(cur.amount)
                        }, 0)
                    })
                    console.log(total)
                    console.log(num)
                    if (num === count) {
                        if (row.amount) {
                            let _t = 0
                            this.wzmxtable.forEach(item => {
                                _t += item.children.reduce((prev, cur) => {
                                    if (
                                        cur.materialId === row.materialId &&
                                        row.changeType !== -1
                                    ) {
                                        return prev + 0
                                    }
                                    return prev + Number(cur.amount)
                                }, 0)
                            })
                            row.amount = +(this.jkkje - _t).toFixed(2)
                            // row.apportionmentRatio =
                        }
                    } else {
                        if (Math.abs(total) > Math.abs(this.jkkje)) {
                            this.clientPop('err', '超出剩余未分摊金额')
                            row.amount = ''
                            row.apportionmentRatio = ''
                        } else {
                            // this.clientPop('err', `剩余未分摊金额 ${Math.abs(this.jkkje - total)}`)
                            row.apportionmentRatio =
                                +((row.amount / this.jkkje) * 100).toFixed(2) ||
                                ''
                            if (num === count - 1) {
                                console.log('只剩最后一项了')
                                for (
                                    let i = 0;
                                    i < this.wzmxtable.length;
                                    i++
                                ) {
                                    for (
                                        let m = 0;
                                        m < this.wzmxtable[i].children.length;
                                        m++
                                    ) {
                                        if (
                                            this.wzmxtable[i].children[m]
                                                .amount === null &&
                                            this.wzmxtable[i].children[m]
                                                .changeType !== -1
                                        ) {
                                            this.wzmxtable[i].children[
                                                m
                                            ].amount = +(
                                                this.jkkje - total
                                            ).toFixed(2)
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else if(str === '比例') {
                    this.wzmxtable.forEach(item => {
                        total += item.children.reduce((prev, cur) => {
                            if (cur.apportionmentRatio !== null) {
                                num++
                            }
                            return prev + Number(cur.apportionmentRatio)
                        }, 0)
                    })
                    if (total > 1) {
                        this.clientPop('err', '超出剩余未分摊比例')
                        row.amount = ''
                        row.apportionmentRatio = ''
                    } else {
                        // this.clientPop('err', `剩余未分摊比例 ${this.jkkje - total}`)
                        row.amount = (
                            this.jkkje * row.apportionmentRatio
                        ).toFixed(2)
                        if (num === count - 1) {
                            console.log('只剩最后一项了')
                        }
                    }
                }
            }
            // if(str === '金额') {
            //     if(+this.jkkje) {
            //         if(this.resultCount === null) {
            //             if(Math.abs(row.amount) > Math.abs(this.jkkje)) {
            //                 this.clientPop('err', `剩余未分摊金额 ${this.jkkje}`)
            //                 row.amount = ''
            //                 row.apportionmentRatio = ''
            //             }else {
            //                 if(this.jkkje < 0) {
            //                     row.amount = -row.amount || ''
            //                 }
            //                 row.apportionmentRatio = Math.abs(+((+row.amount / +this.jkkje) * 100).toFixed(2)) || ''
            //             }
            //         }else{
            //             if(Math.abs(row.amount) > Math.abs(this.resultCount)) {
            //                 this.clientPop('err', `剩余未分摊金额 ${this.resultCount}`)
            //                 row.amount = ''
            //                 row.apportionmentRatio = ''
            //             }else {
            //                 if(this.jkkje < 0) {
            //                     row.amount = -row.amount || ''
            //                 }
            //                 row.apportionmentRatio = Math.abs(+((+row.amount / +this.jkkje) * 100).toFixed(2)) || ''
            //             }
            //         }
            //         this.apportionmentAmountFun()
            //         this.apportionmentRatioFun()
            //     }else {
            //         this.clientPop('err', '请先添加加扣款明细中的加扣款金额')
            //     }
            // }else {
            //     if(+this.jkkje) {
            //         if(this.remainingApportionmentRatio === null) {
            //             if(+row.apportionmentRatio > 100) {
            //                 this.clientPop('err', '剩余未分摊比例 100 %')
            //                 row.amount = ''
            //                 row.apportionmentRatio = ''
            //             }else {
            //                 row.amount = +((row.apportionmentRatio / 100) * this.jkkje).toFixed(2)
            //             }
            //         }else {
            //             if(+row.apportionmentRatio > this.remainingApportionmentRatio) {
            //                 this.clientPop('err', `剩余未分摊比例 ${this.remainingApportionmentRatio} %`)
            //                 row.amount = ''
            //                 row.apportionmentRatio = ''
            //             }else {
            //                 row.amount = +((row.apportionmentRatio / 100) * this.jkkje).toFixed(2)
            //             }
            //         }
            //         this.apportionmentAmountFun()
            //         this.apportionmentRatioFun()
            //     }else {
            //         this.clientPop('err', '请先添加加扣款明细中的加扣款金额')
            //     }
            // }
        },
        // 计算物资明细中剩余分摊金额
        apportionmentAmountFun () {
            let count = 0
            let countSum = 0
            this.wzmxtable.forEach(item => {
                count = item.children.reduce(
                    (prev, c) => (prev += +c.amount || 0),
                    0
                )
                countSum += +count
            })
            this.resultCount = Math.abs(+(+this.jkkje - +countSum).toFixed(2))
        },
        // 计算物资明细中剩余分摊比例
        apportionmentRatioFun () {
            let count = 0
            let countSum = 0
            this.wzmxtable.forEach(item => {
                count = item.children.reduce(
                    (prev, c) => (prev += +c.apportionmentRatio || 0),
                    0
                )
                countSum += +count
            })
            this.remainingApportionmentRatio = Math.abs(
                +(100 - +countSum).toFixed(2)
            )
        },

        // 物资明细删除后隐藏数据行
        tableRowClassNameWZ ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            if (row.children) {
                if (row.children.length < 1) {
                    return 'warning-row'
                } else {
                    let isDel = row.children.every(it => it.changeType === -1)
                    if (isDel) {
                        return 'warning-row'
                    }
                }
            }
            return ''
        },
        // 物资明细全选
        acceptanceSelectAll (selection) {
            this.acceptanceSelects = !this.acceptanceSelects

            this.splite(this.wzmxtable, this.acceptanceSelects)

            // 如果点击全选后,选中数据的长度和原始数组中父级加上changeType不等于-1的子级数据总数相等,就说明是全选选中,否则是全不选中
            let count = 0
            this.wzmxtable.forEach(item => {
                count++
                item.children.forEach(it => {
                    if (it.changeType !== -1) {
                        count++
                    }
                })
            })
            // console.log(count)
            let num = 0
            selection.forEach(item => {
                if (item.changeType) {
                    if (item.changeType !== -1) {
                        num++
                    }
                } else {
                    num++
                }
            })
            // console.log(selection)
            if (num === count) {
                this.acceptanceSelects = true
            } else {
                this.acceptanceSelects = false
            }

            // 如果全选按钮是选中状态,那么父级控制选中与否的字段isChecked就应该是true
            if (this.acceptanceSelects) {
                this.wzmxtable.forEach(i => {
                    i.isChecked = true
                })
            } else {
                this.wzmxtable.forEach(i => {
                    i.isChecked = false
                })
            }
            // 点击全选的时候,把已经删除的子级changType设置为选中,如果某个父级下面所有的子级都为-1,则需要将这个父级的isChecked设置为true
            this.wzlbTableData.forEach(item => {
                item.children.forEach(it => {
                    if (it.changeType === -1) {
                        this.$refs.multipleTable2.toggleRowSelection(it, true)
                    }
                })
                let isCheckedAllChildren = item.children.every(
                    its => its.changeType === -1
                )
                if (isCheckedAllChildren) {
                    this.$refs.multipleTable2.toggleRowSelection(item, true)
                    item.isChecked = true
                }
            })
        },
        splite (data, flag) {
            data.forEach(row => {
                this.$refs.multipleTable2.toggleRowSelection(row, flag)
                if (row.children != undefined) {
                    this.splite(row.children, flag)
                }
            })
        },
        // 当用户手动勾选数据行的 Checkbox 时触发的事件
        selectRow (selection, row) {
            if (row.children) {
                if (row.isChecked) {
                    row.children.forEach(item => {
                        if (item.changeType !== -1) {
                            this.$refs.multipleTable2.toggleRowSelection(
                                item,
                                false
                            )
                        }
                    })
                    row.isChecked = false
                } else {
                    row.children.forEach(item => {
                        if (item.changeType !== -1) {
                            this.$refs.multipleTable2.toggleRowSelection(
                                item,
                                true
                            )
                        }
                    })
                    row.isChecked = true
                }
            } else {
                const _parentId = row.parentId
                let count = 0
                const target = this.wzmxtable.find(i => {
                    if (i.topClassId === _parentId) {
                        i.children.forEach(its => {
                            if (its.changeType !== -1) {
                                count++
                            }
                        })
                        return i
                    }
                })

                const _target = selection.filter(it => {
                    return it.parentId === _parentId && it.changeType !== -1
                })
                if (count === _target.length) {
                    this.$refs.multipleTable2.toggleRowSelection(target, true)
                    target.isChecked = true
                } else {
                    this.$refs.multipleTable2.toggleRowSelection(target, false)
                    target.isChecked = false
                }
            }

            // // 全选判断
            const isAll = this.wzmxtable.every(i => {
                return i.isChecked === true
            })
            if (isAll) {
                this.tableHeadClass = 'tableHeadClass'
                this.acceptanceSelects = true
            } else {
                this.tableHeadClass = 'cancelClass'
                this.acceptanceSelects = false
            }
            // console.log(selection)
        },
        // 复选框选中的数据
        acceptanceSelect () {
            this.acceptanceList = this.$refs.multipleTable2.selection
        },

        // 物资明细删除
        materialsDelete () {
            this.acceptanceList = this.acceptanceList.filter(item => {
                if (item.children) {
                    const isEmpty = item.children.every(i => {
                        return i.changeType === -1
                    })
                    return isEmpty ? false : true
                } else {
                    return item.changeType !== -1
                }
            })
            const length = this.acceptanceList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.acceptanceDeleteList
                )
            }
        },
        // 批量删除
        acceptanceDeleteList () {
            this.acceptanceList.forEach(row => {
                if (row.dtlId) {
                    this.wzmxtable.forEach(item => {
                        const index = item.children.findIndex(
                            its => its.dtlId === row.dtlId
                        )
                        if (index !== -1) {
                            this.$set(item.children[index], 'changeType', -1)
                            this.$set(item.children[index], 'amount', 0)
                            this.$set(
                                item.children[index],
                                'apportionmentRatio',
                                0
                            )
                        }
                    })
                } else {
                    this.wzmxtable.forEach(item => {
                        item.children.forEach((its, index) => {
                            if (this._.isEqual(its, row)) {
                                item.children.splice(index, 1)
                            }
                        })
                    })
                }
            })
            this.$refs.multipleTable2.clearSelection()
            // 删除数据后,需重新计算未分摊金额
            this.apportionmentAmountFun()
            this.apportionmentRatioFun()
        },

        // ==================================返还保证金===========================
        async xzbzj () {
            if (this.formData.settlementUnitId == '') {
                this.clientPop('err', '请选机材合同')
                return
            }
            selectDataClient({
                SelectServiceToken:
                    '/materialsettle/purchaseSettlement/listUnreturnAmountForSelect',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [],
                InitParamsStr: JSON.stringify(), // 接口参数(name为模拟参数)
                Title: '选择保证金' // 标题
            }).then(val => {
                // 保存用户选择返回数据到store
                if (val.length > 0) {
                    let data = val
                    for (let i = 0; i < data.length; i++) {
                        data[i].returnAmount = 0
                        this.bzjtableData.push(data[i])
                    }
                }
            })
        },
        // 返还保证金/说明失去焦点
        marginBlur (row) {
            row.changeType === 1 ? row.changeType = 1 : row.changeType = 2
            if(row.returnAmount > row.previousTotalReturnedAmount) {
                this.clientPop('err', `不可超剩余未返还保证金${row.previousTotalReturnedAmount}`)
                row.returnAmount = row.previousTotalReturnedAmount
            }
        },
        // 保证金复选框选中数据
        marginSelect (selection) {
            this.marginList = selection.filter(
                item => item.changeType !== -1
            )
        },
        // 保证金删除
        marginDelete () {
            const length = this.marginList.length
            if (length === 0) {
                this.clientPop('info', '你还未选择数据,请选择!')
            } else {
                this.clientPop(
                    'info',
                    this.moreDeleteErr(length),
                    this.marginDeleteList
                )
            }
        },
        marginDeleteList () {
            this.marginList.forEach(row => {
                if (row.dtlId) {
                    const index = this.bzjtableData.findIndex(item => {
                        return item.dtlId == row.dtlId
                    })
                    this.$set(this.bzjtableData[index], 'changeType', -1)
                    this.$set(this.bzjtableData[index], 'returnAmount', 0)
                } else {
                    this.bzjtableData.forEach((item, index) => {
                        if (this._.isEqual(item, row)) {
                            this.bzjtableData.splice(index, 1)
                        }
                    })
                }
            })
            this.$refs.marginTableRef.clearSelection()
        },

        // ==================================审核流程====================================
        //获取按钮状态
        getCurrentUnitInfo () {
            publicRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        // 获取审核历史
        async getauditHistory () {
            const data = await publicRequest.getauditHistory({
                billId: this.billId,
                billType: 1019,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            })
            this.shenheArr = data
        },
        // 点击下面按钮
        async exas (arg) {
            if (arg === 'submit') {
                this.saveAll() // 保存所有数据
            } else if (arg === 'submitCommit') {
                await this.submitCommit() // 提交审核
            } else if (arg === 'audit') {
                await this.shenhe() // 审核
            } else if (arg === 'undoAudit') {
                await this.undoAudit() // 撤销审核
            } else if (arg === 'nullify') {
                await this.nullify() // 作废
            } else if (arg === 'deleteData') {
                await this.shanchu() // 删除
            } else if(arg === 'print') {
                this.print() // 打印
            }
        },
        // 保存所有数据
        async saveAll () {
            if (this.$refs.accessory.attachTableData.length < 1) {
                this.clientPop('err', '您还没有上传附件,请上传附件!')
                return
            }
            showLoading()
            try {
                await Promise.all([
                    this.updateBaseInfo(),
                    this.savePlusDeduction(),
                    this.saveSupplies(),
                    this.saveMargin()
                ])
                this.clientPop('suc', '保存成功')
            } catch (err) {
                console.log(err)
            } finally {
                hideLoading()
            }
        },

        // 提交审核
        async submitCommit () {
            try {
                showLoading()
                await Promise.all([
                    this.updateBaseInfo(),
                    this.savePlusDeduction(),
                    this.saveSupplies(),
                    this.saveMargin()
                ])
                await publicRequest.commitexamine(this.auditParams)
                this.clientPop('suc', '提交审核成功', this.handleClose)
            } catch (err) {
                console.log(err)
            } finally {
                hideLoading()
            }
        },
        // 审核
        shenhe () {
            try {
                this.setAuditParams(this.auditParams)
                openAppClient('/exaDialog', '填写审核意见', async () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    showLoading()
                    // 将审核意见赋值给参数传给后端
                    await publicRequest.goaudit(auditParams)
                    this.clientPop('suc', '审核成功', this.handleClose)
                }, null, null, null, 'small')
            } catch (err) {
                this.clientPop('suc', '审核失败')
            } finally {
                hideLoading()
            }
        },
        // 撤销审核
        undoAudit () {
            try {
                this.clientPop('info', '确定返回上一步操作吗?', async () => {
                    showLoading()
                    await publicRequest.goBack(this.auditParams)
                    this.clientPop('suc', '撤回成功', this.handleClose)
                })
            } finally {
                hideLoading()
            }
        },
        // 作废
        nullify () {
            try {
                this.setAuditParams(this.nullifyParams)
                openAppClient('/nullifyDialog', '单据作废原因', async () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    showLoading()
                    await publicRequest.zuofei(auditParams)
                    this.clientPop('suc', '作废成功', this.handleClose)
                }, null, null, null, 'small')
            } finally {
                hideLoading()
            }
        },
        // 删除
        shanchu () {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                async () => {
                    showLoading()
                    await auditRequest
                        .deljkkbyid({ id: this.$route.query.billid })
                        .then(() => {
                            this.clientPop('suc', '删除成功', this.handleClose)
                        })
                        .finally(() => {
                            hideLoading()
                        })
                }
            )
        },

        // 打印
        async print () {
            const printData = async ()=>{
                showLoading()
                try{
                    const  params =  {
                        'reportTitle': '供方加扣款结算单', //报表名
                        'orgName': this.formData.orgName, //单据机构
                        'reportQRUri': '', //报表内容URI
                        'billNo': this.formData.billNo, //单据编码
                        'summaryInfoItems': [ //基本信息
                            { 'label': '供应单位', 'value': this.formData.settlementUnitName, 'isFullRow': false }, //isFullRow:是否占整行
                            { 'label': '附件', 'value': '    ' + '张', 'isFullRow': false },
                            { 'label': '结算依据', 'value': this.formData.contractName, 'isFullRow': false },
                            { 'label': '结算日期', 'value': this.formData.settlementDate, 'isFullRow': false },
                            { 'label': '加扣款合计金额(元)', 'value': this.formData.plusDeductionAmount, 'isFullRow': false },
                            { 'label': '加扣款合计金额大写', 'value': numToChinese(Math.abs(this.formData.plusDeductionAmount)), 'isFullRow': false },
                            { 'label': '备注信息', 'value': this.formData.remarks, 'isFullRow': false },
                            { 'label': '单位', 'value': '元', 'isFullRow': false },
                        ],
                        'tables': [] //表格
                    }
                    // 加扣款明细
                    this.jkktableData.forEach(item => {
                        item.plusDeductionType == 1 ? item.plusDeductionType = '加款' : item.plusDeductionType = '扣款'
                    })
                    const jkkList = {
                        'tableTitle': '加扣款明细',
                        'tableContent': {
                            '加扣款类别': 'plusDeductionType',
                            '加扣款名称': 'plusDeductionName',
                            '规格': 'spec',
                            '单位': 'unit',
                            '加扣款金额': 'amount',
                        },
                        'tableData': this.jkktableData, //表格数据
                    }
                    params.tables.push(jkkList)
                    // 返还保证金
                    const bzjList = {
                        'tableTitle': '返还保证金',
                        'tableContent': {
                            '名称': 'returnDepositName',
                            '返还保证金': 'returnAmount',
                            '截止本期末返还保证金': 'currentTotalReturnedAmount',
                            '说明': 'remarks',
                        },
                        'tableData': this.bzjtableData, //表格数据
                    }
                    params.tables.push(bzjList)
                    //审核历史
                    const historyList = {
                        'tableTitle': '审核历史',
                        'tableContent': {
                            '审核级次': 'unitName',
                            '审核人': 'assignUser',
                            '审核人岗位': 'userTitle',
                            '通知时间': 'notifyTime',
                            '审核时间': 'completeTime',
                            '审核意见': 'opinion',
                        },
                        'tableData': this.shenheArr, //表格数据
                    }
                    params.tables.push(historyList)
                    hideLoading()
                    return params
                }catch(err) {
                    console.log(err)
                    this.clientPop('err', '打印失败')
                    hideLoading()
                }
            }
            const data = await printData()
            webprintReport(data)
        },

        // 保存基本信息
        updateBaseInfo () {
            //进行保存前要把计算的属性设置给对象
            this.$set(this.formData, 'plusDeductionAmount', this.jkkje) //加扣款金额
            this.$set(
                this.formData,
                'rmbReturnDepositAmount',
                this.bzjje
            ) //保证金金额
            this.$set(
                this.formData,
                'baseCurPlusDeductionAmount',
                this.jkkjeBwb
            ) //加扣款金额 本位币
            this.$set(
                this.formData,
                'baseCurReturnDepositAmount',
                this.bzjjeBwb
            ) //保证金金额本位币
            this.$refs.rulesBaseRef.validate(async valid => {
                if (valid) {
                    await auditRequest.update(this.formData)
                } else {
                    return false
                }
            })
        },
        // 保存加扣款
        async savePlusDeduction () {
            // this.setSelectedInfo(this.jkktableData)
            // openAppClient('/showSelectedData', '选择结果')
            await auditRequest.onsavejjk(this.jkktableData)
            await this.getPlusDeduction()
        },
        // 保存物资明细
        async saveSupplies () {
            await auditRequest.onsavewzhz(this.wzmxtable)
            await this.getMaterials()
        },
        // 保存返还保证金
        async saveMargin () {
            await auditRequest.onsavebzj(this.bzjtableData)
            await this.getMargin()
        },

        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        //取消
        handleClose () {
            this.$router.replace('/supplierAddpaymentList')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            this.clickId = e.name //记录每次点击的id
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        showState (state) {
            const _state = this.$store.state.settlementManagement.ysState
            const obj = _state.find(x => x.value === Number(state))
            return obj.label
        }
    },

    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'fhbzj',
            ['planDetail', 'materialDetails', 'technicalParameter'],
            'accessory',
            'auditHistory'
        ]
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(
                            item[0]
                        ).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                                    prevHeight +
                                    document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            //动态改变二级选项卡类名
            arr.forEach((item, index) => {
                if (item instanceof Array) {
                    let tabNavHeight = document.querySelector(
                        '.childTab .el-tabs__nav'
                    )
                        ? document.querySelector('.childTab .el-tabs__nav')
                            .offsetHeight
                        : 0
                    if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
                        this.childTabClass = 'childTab2'
                    } else if (scrollTop <= $idsTop[index][1]) {
                        this.childTabClass = ''
                    } else {
                        this.childTabClass = 'childTab1'
                    }
                }
            })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(
                        item[0]
                    ).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                                prevHeight +
                                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
::v-deep.el-table .warning-row {
    display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}
.childTab {
    ::v-deep .el-tabs__header {
        position: absolute !important;
    }
    ::v-deep .el-tabs__content {
        padding: 0 0 0 20px !important;
    }
}
.childTab1 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: fixed;
                top: 0;
                width: 190px;
            }
        }
    }
}
.childTab2 {
    ::v-deep .el-tabs__header {
        position: absolute !important;
        .el-tabs__nav-scroll {
            position: relative;
            .el-tabs__nav {
                position: absolute;
                bottom: 0;
                width: 100%;
            }
        }
    }
}
</style>
